<!-- 打卡列表 -->
<template>
  <ContainerLayout class="clockin-list">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item label="用户">
          <el-input v-model="queryForm.user" clearable placeholder="请输入" style="width: 100px" />
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader :options="deptList" :props="deptProps" style="width: 290px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="queryForm.timelogCategory" clearable placeholder="选择" style="width: 80px">
            <el-option v-for="item in clockinCategoryList" :key="item.dictValue" :label="`${item.dictLabel}`" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <div class="table-wrap" ref="tableWrap">
        <el-table :data="tableData" scrollbar-always-on style="width: 100%" border :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
          <el-table-column prop="deptName" label="部门" width="150" fixed />
          <el-table-column prop="userNick" label="姓名" width="150" fixed />
          <template v-for="item in tableColumnDate">
            <el-table-column :prop="item.date" resizable :class-name="'week' + item.week">
              <template #header> {{ item.date }} （星期{{ weeks[item.week] }}） </template>
              <el-table-column label="早" width="100" :class-name="'week' + item.week">
                <template #default="scope">
                  <ClockinListTableColumn :row="scope.row" :column-key="item.date" :showType="0" @click="handlerClickTableColumn" />
                </template>
              </el-table-column>
              <el-table-column label="晚" width="100" :class-name="'week' + item.week">
                <template #default="scope">
                  <ClockinListTableColumn :row="scope.row" :column-key="item.date" :showType="1" @click="handlerClickTableColumn" />
                </template>
              </el-table-column>
            </el-table-column>
          </template>
          <el-table-column />
        </el-table>
      </div>
    </div>
  </ContainerLayout>
  <DialogClockIn ref="dialogClockInRef" :clockinCategoryList="clockinCategoryList" @submit-successed="handleDialogSubmitSuccessed" />
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import ContainerLayout from '../layout/ContainerLayout.vue'
import * as utils from '../utils'
import http from '../http'
import { useDeptStore, useClockinCategoryStore, useUsersStore } from '../stores'
import { Refresh, Search } from '@element-plus/icons-vue'
import ClockinListTableColumn from '../components/Clockin/ClockinListTableColumn.vue'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'
import DialogClockIn from '../components/dialog/DialogClockIn.vue'

const dialogClockInRef = ref()
const deptList = ref(useDeptStore().getAllState())
const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })
const clockinCategoryList = ref<{ dictValue: number; dictLabel: string }[]>(useClockinCategoryStore().getAll())
const tableData = ref<any[]>([])
const tableColumnDate = ref<any[]>([])
const tableWrap = ref<HTMLElement | null>(null)
const tableHeight = ref(500)
const queryForm = reactive({
  user: '',
  projectId: '',
  date: [] as Date[],
  deptIds: [] as any[] | number[],
  timelogCategory: '',
})
const weeks = '日一二三四五六'.split('')

/**
 * 初始化部门ID
 */
const initDepIds = () => {
  const list = useDeptStore().getAllListState()
  const item = list.find((res: any) => res.deptId === useUsersStore().getAllState().deptId)
  var deptIds = item.ancestors.split(',').map(Number).slice(1).concat(item.deptId)
  queryForm.deptIds = [deptIds]
}

/**
 * 获取考勤分类列表
 *
 * @returns {Promise<void>}
 */
const getClockinCategoryList = async () => {
  const [start, end] = queryForm.date
  // 设置 table 列
  tableColumnDate.value = utils.generateDates2(start, end)

  const deptIds: any[] = []
  queryForm.deptIds.forEach((e: any) => {
    deptIds.push(e[e.length - 1])
  })
  const params = {
    pageSize: 99999,
    startClockinDate: utils.formatDate(start, 'yyyy-MM-dd'),
    endClockinDate: utils.formatDate(end, 'yyyy-MM-dd'),
  }
  if (queryForm.user !== '') {
    Object.assign(params, { userName: queryForm.user })
  }

  if (queryForm.timelogCategory !== '') {
    Object.assign(params, { timelogCategory: queryForm.timelogCategory })
  }
  if (deptIds.length > 0) {
    Object.assign(params, { deptIds: deptIds.join(',') })
  }

  const { rows } = await http({
    method: 'GET',
    path: '/dev-api/oa/clockin/listbydate',
    params,
  })
  const result: any = {}
  rows.forEach((row: any) => {
    const userId = row.userId
    if (!result[userId]) {
      result[userId] = { ...row }
    }
    const key = `${row.clockinDate}-${row.clockinCategory}`
    result[userId][key] = row.clockinTime.split(' ')[1]
  })

  tableData.value = Object.values(result)
}

/**
 * 重置表单
 *
 * 重置查询表单的所有字段到初始状态，包括用户、项目ID、日期范围、部门ID数组和时间日志类别
 */
const resetForm = async () => {
  tableData.value = []
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本月) as Date[]
  queryForm.user = ''
  queryForm.projectId = ''
  queryForm.date = [start, end]
  queryForm.deptIds = [] as string[] | number[]
  queryForm.timelogCategory = ''
  await initDepIds()
}
/**
 * 处理点击提交按钮的事件
 *
 * 异步调用获取打卡分类列表的函数
 */
const handleClickBtnSubmit = async () => {
  await getClockinCategoryList()
}

/**
 * 处理点击重置按钮的事件
 *
 * 调用 resetForm 函数重置表单
 */
const handleClickBtnReset = async () => {
  await resetForm()
  await handleClickBtnSubmit()
}

const handlerClickTableColumn = (val: any) => {
  if (dialogClockInRef.value) {
    const { userId, deptId, deptName, userName, userNick } = val.row
    dialogClockInRef.value.openDialog({
      date: new Date(val.columnKey),
      clockinCategoryList: clockinCategoryList.value,
      defaultClockinCategory: val.showType.toString(),
      isComp: true,
      checkIsClockIn: -1,
      clickInUser: {
        userId,
        deptId,
        deptName,
        username: userName,
        nickName: userNick,
      },
    })
  }
}

const handleDialogSubmitSuccessed = async () => {
  // await handleClickBtnReset()
  await getClockinCategoryList()
}
onMounted(async () => {
  nextTick(() => {
    const tableWrapElement = tableWrap.value
    if (tableWrapElement) {
      // 设置表格高度
      tableHeight.value = tableWrapElement.offsetHeight
    }
  })
  await resetForm()
  // await getClockinCategoryList()
})
</script>
<style lang="scss" scoped>
.clockin-list {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .table-header-cell {
    writing-mode: vertical-lr;
  }
}
</style>
